﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace Medianamik.UI.Controls
{
	/// <author>
	///	Artiom Chilaru
	/// </author>
	/// <summary>
	/// Client side validation running server side code
	/// </summary>
    /// <seealso cref="http://www.codeproject.com/KB/validation/Async_CustomValidator.aspx"/>
	[ToolboxData("<{0}:AsyncCustomValidator runat=server></{0}:AsyncCustomValidator>")]
	public class AsyncCustomValidator : CustomValidator
	{
		private ScriptManager ScriptManager
		{
			get
			{
				ScriptManager manager = ScriptManager.GetCurrent(this.Page);
				if (manager == null)
				{
					throw new InvalidOperationException(string.Format("The control with ID '{0}' requires a ScriptManager on the page. The ScriptManager must appear before any controls that need it.", new object[] { this.ID }));
				}

				return manager;
			}
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			if (ScriptManager.EnablePageMethods == false)
				throw new InvalidOperationException("The ScriptManager has to have EnablePageMethods set to true to allow the AsyncCustomValidator to work");

			if (!String.IsNullOrEmpty(AsyncWebMethod))
			{
				base.ClientValidationFunction = ClientID + "_Validate";

				String funcs = "\n" +
					"function " + ClientID + "_Validate(source, args)\n" +
					"{\n" +
					(String.IsNullOrEmpty(AsyncWebMethodRunCondition) ? String.Empty :
					"	if(" + AsyncWebMethodRunCondition + ")\n\t") +
					"	PageMethods." + AsyncWebMethod + "(args.Value, " + ClientID + "_Succedeed);\n" +
					"}\n" +
					"function " + ClientID + "_Succedeed(res)\n" +
					"{\n" +
					"	document.getElementById('" + ClientID + "').isvalid=res;\n" +
					"	ValidatorUpdateDisplay(document.getElementById('" + ClientID + "'));\n" +
					"}";
				Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_Scripts", funcs, true);
			}
		}

		public string AsyncWebMethod
		{
			get
			{
				return (string)this.ViewState["AsyncWebMethod"] ?? String.Empty;
			}
			set
			{
				this.ViewState["AsyncWebMethod"] = value;
			}
		}

		public String AsyncWebMethodRunCondition
		{
			get
			{
				return (string)this.ViewState["AsyncWebMethodRunCondition"] ?? String.Empty;
			}
			set
			{
				this.ViewState["AsyncWebMethodRunCondition"] = value;
			}
		}

		public new String ClientValidationFunction
		{
			get
			{
				return base.ClientValidationFunction;
			}
			set
			{
				throw new InvalidOperationException("Cannot override the ClientValidationFunction.");
			}
		}
	}
}
